(function($, win, doc, undefined){

	var aesPwd = 'Xxeicq3gknHJEsZR';
	var app = null;

	/**
	 *  默认值：/seeyon
	 */
	var appBasePath = (function(){
		
		var path = location.pathname;
		
		return path.substring(0, path.indexOf('/', 1));
	})();
	
	function getDialog(){
		
		return  win.parentDialogObj && win.parentDialogObj["ctrlDialog"];
	}
	
	function getTransParams(){
				
		return getDialog().getTransParams();
	}
	
	var sqlMirror = (function (){
		
		var editor = null;
		var script = null;

		return {
			init: function(){
				
				setTimeout(function(){
					
					if(null != editor){
						
						$.setCSS(editor.getWrapperElement(), {display: 'block'});
						
						return;
					}
					
					if(script){
						$.setEleValue('#script_content', script);
					}
					
					editor = CodeMirror.fromTextArea($.getElement('#script_content'), {
						mode: 'text/x-sql',
						theme: "darcula",
						lineNumbers: true,
						lineWrapping: true
					});
					
					editor.refresh();
					
				}, 200);
			},
			setValue: function(_script){
				
				script = $.aes_decrypt((_script ? decodeURIComponent(_script) : ''), aesPwd);
				
				if(null == editor){
					return ;
				}
				
				editor.setValue(script);
			},
			getValue: function(){
				return $.aes_encrypt((editor ? editor.getValue() : script), aesPwd);
			},
			getPlaintext: function(){
				return (editor ? editor.getValue() : script);
			},
			close: function(){
				editor && $.setCSS(editor.getWrapperElement(), {display: 'none'});
			}
		}
	})();
	
	var groovyMirror = (function (){
		
		var editor = null;
		var script = null;

		return {
			init: function(){
				
				setTimeout(function(){
					
					if(null != editor){
						
						$.setCSS(editor.getWrapperElement(), {display: 'block'});
						
						return;
					}
					
					if($.isBlank(script)){
						
						$.setEleValue('#script_content', (function(){
							
							var scriptTxt = ['#!/snail/common/utils groovy GETDATA_' + $.random20L()];
							scriptTxt.push('');
							scriptTxt.push('import com.seeyon.ctp.common.AppContext;');
							scriptTxt.push('import com.seeyon.apps.snail.APPLogger;');
							scriptTxt.push('import com.seeyon.apps.snail.common.MessageHepler;');
							scriptTxt.push('');
							scriptTxt.push('import snail.common.ClassHelper;');
							scriptTxt.push('import snail.common.ServiceException;');
							scriptTxt.push('import snail.common.utils.StringHelper;');
							scriptTxt.push('import snail.common.utils.JSONHelper;');
							scriptTxt.push('import snail.common.utils.DateHelper;');
							scriptTxt.push('import snail.common.utils.IDHelper;');
							scriptTxt.push('import snail.common.utils.MapHelper;');
							scriptTxt.push('import snail.common.web.HTTPHelper;');
							scriptTxt.push('');
							scriptTxt.push('');
							scriptTxt.push('/**');
							scriptTxt.push(' * @param name 名称');
							scriptTxt.push(' * @param code 编码');
							scriptTxt.push(' */');
							scriptTxt.push('static main(args){');
							scriptTxt.push('    ');
							scriptTxt.push('    ');
							scriptTxt.push('	if(__GETDATA_TREE__){ // 树数据');
							scriptTxt.push('        ');
							scriptTxt.push('		return null;');
							scriptTxt.push('	}else{ // 列表数据');
							scriptTxt.push('        ');
							scriptTxt.push('        ');
							scriptTxt.push('		return [[');
							scriptTxt.push('		     name: "名称", code: "编码", data: "数据", data2: null, data3: null');
							scriptTxt.push('		],[');
							scriptTxt.push('	         name: "名称2", code: "编码2", data: "数据2", data2: null, data3: null');
							scriptTxt.push('	    ]];');
							scriptTxt.push('	}');
							scriptTxt.push('    ');
							scriptTxt.push('}');
							scriptTxt.push('');
							scriptTxt.push('');
							scriptTxt.push('');
							scriptTxt.push('/** ******************************* 以下为共公函数 ******************************* */');
							scriptTxt.push('include seeyon.common.groovy;');
							scriptTxt.push('');
							
							return scriptTxt.join('\r\n');
						})());
						
					}else{
						$.setEleValue('#script_content', script);
					}
					
					editor = CodeMirror.fromTextArea($.getElement('#script_content'), {
						mode: 'text/x-groovy',
						theme: "darcula",
						lineNumbers: true,
						lineWrapping: true,
						indentUnit: 4,
						extraKeys: {
							'Ctrl': 'autocomplete'
						},
						hintOptions: {
							completeSingle: false,
							hint: $.codemirror.groovyShowHint,
							word: {
								__WORD_LIST__: [
									'getObjBySQL(sqlStr, closure, nodata_closure=null)', 'getObjBySQL(sqlStr, args, closure, nodata_closure)', 
									'getListBySQL(sqlStr, closure, nodata_closure=null)', 'getListBySQL(sqlStr, args, closure, nodata_closure)',
									'getSQLClient()', 'sendMessage(txt, receiver=null)', 'logger(txt)', 'GLOBALS(key, value=null)', 'NVL(obj, Object... obj2)'
								]
							}
						}
					});
					
					editor.on('keypress', function(){
						//编译器内容更改事件
						editor.showHint();
					});
					
					editor.refresh();
					
				}, 200);
			},
			setValue: function(_script){
				
				script = $.aes_decrypt((_script ? decodeURIComponent(_script) : ''), aesPwd);;
				
				if(null == editor){
					return ;
				}
				
				editor.setValue(script);
			},
			getValue: function(){
				return $.aes_encrypt((editor ? editor.getValue() : script), aesPwd);
			},
			getPlaintext: function(){
				return (editor ? editor.getValue() : script);
			},
			close: function(){
				editor && $.setCSS(editor.getWrapperElement(), {display: 'none'});
			}
		}
	})();
	
	
	var httpMirror = (function (){
		
		var editor = null;
		var script = null;

		return {
			init: function(){
				
				setTimeout(function(){
					
					if(null != editor){
						
						$.setCSS(editor.getWrapperElement(), {display: 'block'});
						
						return;
					}
					
					if($.isBlank(script)){
						
						$.setEleValue('#script_content', (function(){
							
							var scriptTxt = ['GET /seeyon/data?param=${value}&param2=${value2} HTTP/1.1'];
							scriptTxt.push('Host: 127.0.0.1');
							scriptTxt.push('Content-Type: application/x-www-form-urlencoded;charset=utf-8');
							scriptTxt.push('Accept: application/json');
							scriptTxt.push('User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)');
							scriptTxt.push('token: ${tokenvalue}');
							scriptTxt.push('\r\n');
							scriptTxt.push('');
							
							return scriptTxt.join('\r\n');
						})());
						
					}else{
						$.setEleValue('#script_content', script);
					}
					
					editor = CodeMirror.fromTextArea($.getElement('#script_content'), {
						mode: 'message/http',
						theme: "darcula",
						lineNumbers: true,
						lineWrapping: true
					});
					
					editor.refresh();
					
				}, 200);
			},
			setValue: function(_script){
				
				script = $.aes_decrypt((_script ? decodeURIComponent(_script) : ''), aesPwd);
				
				if(null == editor){
					return ;
				}
				
				editor.setValue(script);
			},
			getValue: function(){
				
				var value = (editor ? editor.getValue() : script);
				value = value.replace(/\r/g, '').replace(/\n/g, '\r\n');
				
				return $.aes_encrypt(value, aesPwd);
			},
			getPlaintext: function(){

				var value = editor.getValue();
				value = value.replace(/\r/g, '').replace(/\n/g, '\r\n');
				
				return value;
			},
			close: function(){
				editor && $.setCSS(editor.getWrapperElement(), {display: 'none'});
			}
		}
	})();
	
	
	/**
	 * 初始化窗口
	 */
	function initWindow(){
		
		var dialog = $.getElement('div[laytype="dialog"]', 0, window.parent.document);
				
		var width = window.screen.width || window.screen.availWidth;
		
		if(1440 < width){
			
			$.setCSS(dialog, {
				width: 'calc(100% - 100px)', height: 'calc(100% - 70px)',
				top: '35px', left: '50px'
			});
			
		}else{
			
			$.setCSS(dialog, {
				width: 'calc(100% - 50px)', height: 'calc(100% - 20px)',
				top: '10px', left: '25px'
			});
		}

		var dialogWindow = $.getElement('div[laytype="dialog"]>div:nth-child(2)', 0, window.parent.document);
		
		$.setCSS(dialogWindow, {
			height: 'calc(100% - 105px)'
		});
		
		dialogWindow = $.getElement('div[laytype="dialog"]>div:nth-child(2)>iframe', 0, window.parent.document);
		
		$.setCSS(dialogWindow, {
			height: '100%'
		});
		
		var dialogTitle = $.getElement('div[laytype="dialog"]>div:first-child', 0, window.parent.document);
		
		$.cleanHtml(dialogTitle);
		$.appendHtml(dialogTitle, 'GetDATA 配置器');
	}
	
	/**
	 * 初始化窗口
	 */
	function initVue(){
		
		app = new Vue({
			el: '#app',
			data: {
				style:{
					selectedIndex: 'first'
				},
				basic:{
					isUpdate: false,
					auth: null,
					mark: null,
					db: 'A8',
					inDataTableIndex: 0,
					outDataTableIndex: 0
				},
				formTableSelect:{
					props: {}, 
					options: [
						{ id: '...', value: '...', label: '...' }
					]
				},
				formFieldSelect:{
					props: {}, 
					groups:[
						{	
							label: '默认',
							options: [
								{ id: '...', value: '...', label: '...' }
							]
						}
					]
				},
				datasetFieldSelect:{
					props: {}, 
					options: [
						{ id: '...', value: '...', label: '...' }
					]
				},
				db:{
					tableData:[
						{
							id: null,
							name: '...',
							product: '...',
							driver_type: 'JDBC',
							driver_class: '...',
							driver_url: '...',
							username: '...',
							password: '...',
							mark: '...',
							description: '...'
						}
					],
					formData:{
						fields:{
							id: null,
							name: '',
							product: '',
							driver_type: 'JDBC',
							driver_class: '',
							driver_url: '',
							username: '',
							password: '',
							mark: '',
							description: ''
						},
						rules: {
						  name: [
							  { required: true, message: '请输入名称', trigger: 'blur' },
							  { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
						  ],
						  product: [
							  { required: true, message: '请选择数据库类型', trigger: 'change' }
						  ],
						  driver_class: [
							  { required: true, message: '请输入驱动类名', trigger: 'blur' }
						  ],
						  driver_url: [
							  { required: true, message: '请输入数据源URL', trigger: 'blur' }
						  ],
						  username: [
							  { required: true, message: '请输入用户名', trigger: 'blur' }
						  ],
						  mark: [
							  { required: true, message: '请输入连接标识', trigger: 'blur' }
						  ]
						}
					}
				},
				dataset:{
					inTableData:[
						{
							key: '...',
							name: '...',
							inKey: null,
							type: 'string',
							defaultValue: null
						}
					],
					outTableData:[
						{
							key: '...',
							name: '...',
							width: 200,
							unique: false,
							display: true,
							lock: false,
							example: '...'
						}
					],
					formData:{
						fields:{
							name: '',
							type: 'sql'
						},
						rules: {
							name: [
								{ required: true, message: '请输入名称', trigger: 'blur' }
							],
							type: [
								{ required: true, message: '请选择数据集类型', trigger: 'change' }
							]
						}
					},
					quote: {
						dialogVisible: false,
						value: null,
						config: null,
						cache: null
					}
				},
				mapping:{
					fieldTableData:{
						props: {
							children: 'children', hasChildren: 'hasChildren'
						},
						data: [
							{
								key: '...',
								name: '...',
								inKey: '...',
								editable: true,
								defaultValue: null
							}
						]
					}
				},
				other:{
					formData:{
						fields:{
							button: {
								name: null,
								type: null,
								position: null
							},
							formField: {
								lock: 1,
								silent: 0
							}
						},
						rules: {}
					}
				}
			},
			methods:{
				init: function(){
					
					this.loadFormFields();
					
					this.loadConifg();
					
					this.loadDBList();
				},
				loadFormFields: function(){

					var transParams = getTransParams();
					var currentfield = transParams.currentfield;
					var formBaseInfo = transParams.formBaseInfo;
					
					this.basic.mark = currentfield.id;
					
					this.dataset.formData.fields.name = formBaseInfo.bizConfigName
						+ '-' + formBaseInfo.formBaseInfo.formInfo.formName
						+ '-' + currentfield.display;
					
					var tableInfo = formBaseInfo.formBaseInfo.tableInfo;
					
					this.formTableSelect.options = [{
						key: tableInfo.front_formmain.tableName,
						value: (tableInfo.front_formmain.tableName + '|' + tableInfo.front_formmain.frontTableName),
						label: ('[主表] ' + tableInfo.front_formmain.display)
					}];
					
					this.formFieldSelect.groups = [{
						key: tableInfo.front_formmain.tableName,
						label: '主表',
						options: []
					}];
					
					this.mapping.fieldTableData.data = [{
						id: tableInfo.front_formmain.tableName, 
						key: tableInfo.front_formmain.tableName, 
						name: ('主表-' + tableInfo.front_formmain.display),
						inKey: null,
						defaultValue: '',
						tableName: tableInfo.front_formmain.tableName,
						frontTableName: tableInfo.front_formmain.frontTableName,
						children: []
					}];
					

					var _this = this;
					
					tableInfo.front_formmain.fieldInfo.forEach(function(field){
							
						_this.formFieldSelect.groups[0].options.push({ id: field.id, value: (tableInfo.front_formmain.tableName + '.' + field.name), label: field.display });
						
						_this.mapping.fieldTableData.data[0].children.push({
							id: (tableInfo.front_formmain.tableName + '.' + field.name), 
							key: field.name, 
							name: field.display,
							inKey: null,
							editable: true,
							defaultValue: '',
							tableName: tableInfo.front_formmain.tableName,
							frontTableName: tableInfo.front_formmain.frontTableName
						});
					});
					
					var index = 0;
					
					tableInfo.formsons.forEach(function(tableInfo){
						
						var tableName = tableInfo.tableName;
						
						_this.formTableSelect.options.push({
							key: tableName,
							value: (tableName + '|' + tableInfo.frontTableName),
							label: ('[子表] ' + tableInfo.display)
						});
						
						_this.formFieldSelect.groups.push({
							key: tableName,
							label: '子表-' + tableInfo.display,
							options: []
						});
						
						_this.mapping.fieldTableData.data.push({
							id: tableName, 
							key: tableName, 
							name: ('子表-' + tableInfo.display),
							inKey: null,
							defaultValue: null,
							tableName: tableName,
							frontTableName: tableInfo.frontTableName,
							children: []
						});
						
						index++;
						
						tableInfo.fieldInfo.forEach(function(field){
							
							_this.formFieldSelect.groups[index].options.push({ id: field.id, value: (tableName + '.' + field.name), label: field.display });
							
							_this.mapping.fieldTableData.data[index].children.push({
								id: (tableName + '.' + field.name), 
								key: field.name, 
								name: field.display,
								inKey: null,
								editable: true,
								defaultValue: '',
								tableName: tableName,
								frontTableName: tableInfo.frontTableName,
							});
						});
					});

				},
				loadConifg: function(){

					var _this = this;
					
					$.http.get({
						url: (appBasePath + '/snail/formext/getdata.do?method=getConfig'),
						header: {'Accept': 'application/json'},
						data:{mark: this.basic.mark},
						onsuccess: function(result, status, xhr){
							
							var data = null;
							
							if(200 == result.code){
								
								data = result.data;
								
							}else{
								alert(result.message);
							}
							
							if(null == data){
								
								var transParams = getTransParams();
								
								data = (transParams ? (transParams.params ? transParams.params.config : null) : null);
							}
							
							if(null != data){
								
								_this.basic.db = data.db;
								_this.basic.auth = data.auth;
								
								_this.dataset.formData.fields.name = data.dataset.script.name;
								_this.dataset.formData.fields.type = data.dataset.script.type;
								
								if('groovy' == data.dataset.script.type){
									
									groovyMirror.setValue(data.dataset.script.script);
									
								}else if('http' == data.dataset.script.type){
									
									httpMirror.setValue(data.dataset.script.script);
									
								}else{
									
									sqlMirror.setValue(data.dataset.script.script);
								}
								
								_this.dataset.inTableData = data.dataset['in'];
								_this.dataset.outTableData = data.dataset['out'];
								
								
								for(var i=0,len=_this.mapping.fieldTableData.data.length; i<len; i++){

									for(var j=0,jlen=_this.mapping.fieldTableData.data[i].children.length; j<jlen; j++){
										
										for(var k=0,klen=data.mapping.data.length; k<klen; k++){
											
											if(_this.mapping.fieldTableData.data[i].children[j].id == data.mapping.data[k].id){

												_this.mapping.fieldTableData.data[i].children[j].inKey = data.mapping.data[k].inKey;
												_this.mapping.fieldTableData.data[i].children[j].editable = data.mapping.data[k].editable;
												_this.mapping.fieldTableData.data[i].children[j].defaultValue = data.mapping.data[k].defaultValue;
											}
										}
									}
								}

								for(var name in _this.other.formData.fields){
									
									if(data.other[name]){

										_this.other.formData.fields[name] = data.other[name];
									}
								}
								
							}
							
						},
						onerror: function(responseText, status, xhr){
							
							console.log(responseText);
							
							alert('服务异常，STATUS: ' + status);
						}
					});
				},
				loadDBList: function(){
					
					var _this = this;
					
					$.http.get({
						url: (appBasePath + '/snail/formext/getdata.do?method=getDBInfoList'),
						header: {'Accept': 'application/json'},
						onsuccess: function(result, status, xhr){
							
							if(200 == result.code){
								
								_this.db.tableData=result.data;
								
							}else{
								alert(result.message);
							}
						},
						onerror: function(responseText, status, xhr){
							
							console.log(responseText);
							
							alert('服务异常，STATUS: ' + status);
						}
					});
				},
				getGetDATA: function(){
					
					var data = {
						mark: this.basic.mark,
						db: this.basic.db,
						auth: this.basic.auth,
						dataset: {
							script: {
								name: this.dataset.formData.fields.name,
								type: this.dataset.formData.fields.type,
								script: (function(value){
									
									if('groovy' == value){
										
										return groovyMirror.getValue();
										
									}else if('http' == value){
										
										return httpMirror.getValue();
										
									}else{
										
										return sqlMirror.getValue();
									}
								
								})(this.dataset.formData.fields.type)
							},
							"in": this.dataset.inTableData,
							out: this.dataset.outTableData
						},
						mapping: {
							data: (function(fieldTableData){
								
								var data = [];
								
								for(var i=0,len=fieldTableData.length; i<len; i++){
									
									for(var j=0,jlen=fieldTableData[i].children.length; j<jlen; j++){
										
										if(!$.isBlank(fieldTableData[i].children[j].inKey)){
											
											data.push(fieldTableData[i].children[j]);
										}
									}
								}
								
								return data;
							})(this.mapping.fieldTableData.data)
						},
						other: (function(config){
							
							var data = {};
							
							data['button'] = config.formData.fields.button;
							data['formField'] = config.formData.fields.formField;

							return data;
						})(this.other)
					};
				
					return data;
				},
				getDBInfoData: function(){
					
					var data = {};
					
					$.extend(data, this.db.formData.fields);
				
					return data;
				},
				setDBInfoData: function(data){
					
					$.extend(this.db.formData.fields, data, true);
					
				},
				onDBProductChang: function(value){
					
					if('MYSQL' == value){
						
						this.db.formData.fields.driver_class = 'com.mysql.jdbc.Driver';
						this.db.formData.fields.driver_url = 'jdbc:mysql://[IP]:[PORT|3306]/[DBNAME]?useUnicode=true&characterEncoding=utf8';
						
					} else if('MYSQL6X' == value) {
						
						this.db.formData.fields.driver_class = 'com.mysql.cj.jdbc.Driver';
						this.db.formData.fields.driver_url = 'jdbc:mysql://[IP]:[PORT|3306]/[DBNAME]?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false';
						
					} else if('ORACLE' == value) {
						
						this.db.formData.fields.driver_class = 'oracle.jdbc.driver.OracleDriver';
						this.db.formData.fields.driver_url = 'jdbc:oracle:thin:@[IP]:[PORT|1521][/SERVICE_NAME|:SID]';
						
					} else if('SQLSERVER' == value) {
						
						this.db.formData.fields.driver_class = 'com.microsoft.sqlserver.jdbc.SQLServerDriver';
						this.db.formData.fields.driver_url = 'jdbc:sqlserver://[IP]:[PORT|1433];DatabaseName=[DBNAME]';
						
					} else if('POSTGRESQL' == value) {
						
						this.db.formData.fields.driver_class = 'org.postgresql.Driver';
						this.db.formData.fields.driver_url = 'jdbc:postgresql://[IP]:[PORT|5432]/[DBNAME]';
						
					} else if('DB2' == value) {
						
						this.db.formData.fields.driver_class = 'com.ibm.db2.jcc.DB2Driver';
						this.db.formData.fields.driver_url = 'jdbc:db2://[IP]:[PORT|5000]/[DBNAME]';
						
					} else if('DM' == value) {
						
						this.db.formData.fields.driver_class = 'dm.jdbc.driver.DmDriver';
						this.db.formData.fields.driver_url = 'jdbc:dm://[IP]:[PORT|5236]/[DBNAME]';
						
					} else if('KINGBASE' == value) {
						
						this.db.formData.fields.driver_class = 'com.kingbase8.Driver';
						this.db.formData.fields.driver_url = 'jdbc:kingbase8://[IP]:[PORT|54321]/[DBNAME]';
						
					} else if('OSCAR' == value) {
						
						this.db.formData.fields.driver_class = 'com.oscar.Driver';
						this.db.formData.fields.driver_url = 'jdbc:oscar://[IP]:[PORT|2003]/[DBNAME]';
					}
				},
				onTabsChange: function(tab, event){
					
					if('second' == tab.name){
						
						if('groovy' == this.dataset.formData.fields.type){
							
							groovyMirror.init();
							
						}else if('http' == this.dataset.formData.fields.type){
							
							httpMirror.init();
							
						}else{
							
							sqlMirror.init();
						}
					}else if('thirdly' == tab.name){
						
						var param = [];
						
						for(var i=0,len=this.dataset.outTableData.length; i<len; i++){
							
							param.push({ 
								id: this.dataset.outTableData[i].key, 
								value: this.dataset.outTableData[i].key, 
								label: this.dataset.outTableData[i].name
							});
						}
						
						this.datasetFieldSelect.options = param;
					}
				},
				onInDataTableChange: function(currentRow, oldCurrentRow){
					
					if(!currentRow){
						return;
					}
					
					this.basic.inDataTableIndex = (currentRow.index || 1) - 1;
				},
				onUpMoveInData: function(){
					
					if(0 >= this.basic.inDataTableIndex){
						return ;
					}
					

					var newDataList = this.cloneOutData(this.dataset.inTableData);
					
					this.moveDataList(this.basic.inDataTableIndex, -1, newDataList);
					
					this.dataset.inTableData = newDataList;
					
					this.basic.inDataTableIndex--;
				},
				onDnMoveInData: function(){
					
					if(this.basic.inDataTableIndex >= this.dataset.inTableData.length-1){
						return ;
					}
					
					
					var newDataList = this.cloneOutData(this.dataset.inTableData);
					
					this.moveDataList(this.basic.inDataTableIndex, 1, newDataList);
					
					this.dataset.inTableData = newDataList;
					
					this.basic.inDataTableIndex++;
				},
				onOutDataTableChange: function(currentRow, oldCurrentRow){
					
					if(!currentRow){
						return;
					}
					
					this.basic.outDataTableIndex = (currentRow.index || 1) - 1;
				},
				onUpMoveOutData: function(){
					
					if(0 >= this.basic.outDataTableIndex){
						return ;
					}
					

					var newDataList = this.cloneOutData(this.dataset.outTableData);
					
					this.moveDataList(this.basic.outDataTableIndex, -1, newDataList);
					
					this.dataset.outTableData = newDataList;
					
					this.basic.outDataTableIndex--;
				},
				onDnMoveOutData: function(){
					
					if(this.basic.outDataTableIndex >= this.dataset.outTableData.length-1){
						return ;
					}
					
					
					var newDataList = this.cloneOutData(this.dataset.outTableData);
					
					this.moveDataList(this.basic.outDataTableIndex, 1, newDataList);
					
					this.dataset.outTableData = newDataList;
					
					this.basic.outDataTableIndex++;
				},
				cloneOutData: function(dataList){
					
					var newData = null;
					var newDataList = [];	
					
					for(var i=0,len=dataList.length; i<len; i++){
						
						newData = {};
						
						for(var n in dataList[i]){
							
							newData[n] = dataList[i][n];
						}
					
						newDataList.push(newData);
					}
					
					return newDataList;
				},
				moveDataList: function(index, step, dataList){
					
					if(step < 0){
						
						if(0 >= index){
							return ;
						}
						
						var temp = dataList[index-1];
						dataList[index-1] = dataList[index];
						dataList[index] = temp;
						
					}else if(step > 0){
						
						if(index >= dataList.length-1){
							return ;
						}
						
						var temp = dataList[index];
						dataList[index] = dataList[index+1];
						dataList[index+1] = temp;
					}
					
					for(var i=0,len=dataList.length; i<len; i++){
						
						dataList[i].index = i + 1;
					}
				},
				onDatasetChange: function(value){
					
					if('groovy' == value){

						sqlMirror.close();
						httpMirror.close();
						
						groovyMirror.init();
						
					}else if('http' == value){

						sqlMirror.close();
						groovyMirror.close();
						
						httpMirror.init();
						
					}else{

						httpMirror.close();
						groovyMirror.close();
						
						sqlMirror.init();
					}
				},
				onSave: function(){
					
					var _this = this;
					
					$.http.post({
						url: (appBasePath + '/snail/formext/getdata.do?method=saveConfig'),
						header: {'Content-Type': 'application/json', 'Accept': 'application/json'},
						data: this.getGetDATA(),
						onsuccess: function(result, status, xhr){
							
							alert(result.message);
							
						},
						onerror: function(responseText, status, xhr){
							
							console.log(responseText);
							
							alert('服务异常，STATUS: ' + status);
						}
					});
					
				},
				onTestDB: function(){
					
					var _this = this;
					
					$.http.post({
						url: (appBasePath + '/snail/formext/getdata.do?method=testDB'),
						header: {'Content-Type': 'application/json', 'Accept': 'application/json'},
						data: this.getDBInfoData(),
						onsuccess: function(result, status, xhr){
							
							alert(result.message);
							
						},
						onerror: function(responseText, status, xhr){
							console.log(responseText);
						}
					});
				},
				onSaveDB: function(){
					
					var _this = this;
					
					this.$refs.dbFormData.validate(function(valid){
						
						if(valid){

							$.http.post({
								url: (appBasePath + '/snail/formext/getdata.do?method=saveDBInfo'),
								header: {'Content-Type': 'application/json', 'Accept': 'application/json'},
								data: _this.getDBInfoData(),
								onsuccess: function(result, status, xhr){
									
									alert(result.message);
									
									_this.loadDBList();
								},
								onerror: function(responseText, status, xhr){
									console.log(responseText);
								}
							});
						}else{

							alert('数据校验不通过！');
						}
					});
				},
				onSelectDB: function(index, row){
					
					this.basic.db = row.mark;
				},
				onDBEdit: function(index, row){
					
					this.setDBInfoData(row);
					
				},
				onDBDelete: function(index, row){
					
					;
				},
				onTestDatasetConf: function(){
					
					var _this = this;
					
					var fnSuccess = function(result, status, xhr){
						
						if(200 == result.code){
							
							if(result.data && 0 < result.data.length){

								var param = [];
								
								for(var k in result.data[0]){
									
									param.push(
										(function(data, oldDataList){
											
											if(!oldDataList){
												return data;
											}
											
											for(var i=0,len=oldDataList.length; i<len; i++){
												
												if(data.key == oldDataList[i].key){

													data.name = oldDataList[i].name;
													data.width = oldDataList[i].width;
													data.display = oldDataList[i].display;
													data.lock = oldDataList[i].lock;
												}
											}
											
											return data;
										})({
											key: k,
											name: k,
											width: 200,
											unqiue: false,
											display: true,
											lock: false,
											example: result.data[0][k]
										}, _this.dataset.outTableData)
									);
								}
								
								_this.dataset.outTableData = param;
							}
							
						} else {
							alert(result.message);
						}
						
					};
					
					if('groovy' == this.dataset.formData.fields.type){
						
						$.http.post({
							url: (appBasePath + '/snail/formext/getdata.do?method=getData&mark=' + this.basic.mark),
							header: {
								'Content-Type': 'application/json', 'Accept': 'application/json'
							},
							data: (function(config){
								
								var param = {
										pagination:{
											page: 1,
											per_page_size: 1
										}
								};
								
								for(var i=0,len=config.length; i<len; i++){
									param[config[i].key] = config[i].defaultValue;
								}
								
								return param;
							})(this.dataset.inTableData),
							onsuccess: fnSuccess,
							onerror: function(responseText, status, xhr){
								
								console.log(responseText);
								
								alert('服务异常，STATUS: ' + status);
							}
						});
						
					}else if('http' == this.dataset.formData.fields.type){
						
						$.http.post({
							url: (appBasePath + '/snail/formext/getdata.do?method=getData&mark=' + this.basic.mark),
							header: {
								'Content-Type': 'application/json', 'Accept': 'application/json'
							},
							data: (function(config){
								
								var param = {
										pagination:{
											page: 1,
											per_page_size: 1
										}
								};
								
								for(var i=0,len=config.length; i<len; i++){
									param[config[i].key] = config[i].defaultValue;
								}
								
								return param;
							})(this.dataset.inTableData),
							onsuccess: fnSuccess,
							onerror: function(responseText, status, xhr){
								
								console.log(responseText);
								
								alert('服务异常，STATUS: ' + status);
							}
						});
						
					}else{
						
						$.http.post({
							url: (appBasePath + '/snail/formext/getdata.do?method=getData&mark=' + this.basic.mark),
							header: {
								'Content-Type': 'application/json', 'Accept': 'application/json',
								'pagination.page': 1, 'pagination.per_page_size': 1
							},
							data: (function(config){
								
								var param = {};
								
								for(var i=0,len=config.length; i<len; i++){
									
									if('like' == config[i].type){
										param[config[i].key] = ($.isBlank(config[i].defaultValue) ? '%%' : ('%' + config[i].defaultValue + '%'));
									}else{
										param[config[i].key] = config[i].defaultValue;
									}
								}
								
								return param;
							})(this.dataset.inTableData),
							onsuccess: fnSuccess,
							onerror: function(responseText, status, xhr){
								
								console.log(responseText);
								
								alert('服务异常，STATUS: ' + status);
							}
						});
					}
					
				},
				onSaveDatasetConf: function(){

					var param = [];
					
					if('groovy' == this.dataset.formData.fields.type){
						
						var txt = groovyMirror.getPlaintext();
						
						// 提取第一段注解
						var index = txt.indexOf('/*');
						
						if(-1 != index){
							
							txt = txt.substring(index, (txt.indexOf('*/', index) + 2));
							
							var temp = {};
							
							var paramkeys = txt.match(/@param\s+[a-zA-Z_0-9]*\s+[^\r\n]+/g);
							
							if(null != paramkeys){
								
								for(var i=0,len=paramkeys.length; i<len; i++){
									
									paramkeys[i] = paramkeys[i].split(/\s+/);
										
									var paramkey = paramkeys[i][1];
									var paramname = (2 < paramkeys[i].length ? paramkeys[i][2] : null);
									
									if(!temp[paramkey]){
										
										var oldIndex = -1;
										
										for(var j=0,jlen=this.dataset.inTableData.length; j<jlen; j++){
											
											if(this.dataset.inTableData[j].key == paramkey){
												oldIndex = j;
											}
										}
										
										param.push({
											key: paramkey,
											name: ((-1 == oldIndex) ? paramname : this.dataset.inTableData[oldIndex].name),
											inKey: ((-1 == oldIndex) ? null : this.dataset.inTableData[oldIndex].inKey),
											type: ((-1 == oldIndex) ? 'string' : this.dataset.inTableData[oldIndex].type),
											defaultValue: ((-1 == oldIndex) ? null : this.dataset.inTableData[oldIndex].defaultValue)
										});
										
										temp[paramkey] = true;
									}
								}
							}else{
								alert('未检测到一个参数字段！建议至少一个，不超个三个。');
							}
							
						}else{
							alert('未检测到一个参数字段！建议至少一个，不超个三个。');
						}
						
						
					}else if('http' == this.dataset.formData.fields.type){
						
						var txt = httpMirror.getPlaintext();
						
						var paramkeys = txt.match(/\$\{\s*[a-zA-Z_0-9]+\s*\}/g);
						
						if(null != paramkeys){
							
							var temp = {};
							
							for(var i=0,len=paramkeys.length; i<len; i++){
								
								var paramkey = paramkeys[i].substring(2, paramkeys[i].length-1).trim();
									
								if(!temp[paramkey]){
									
									var oldIndex = -1;
									
									for(var j=0,jlen=this.dataset.inTableData.length; j<jlen; j++){
										
										if(this.dataset.inTableData[j].key == paramkey){
											oldIndex = j;
										}
									}
									
									param.push({
										key: paramkey,
										name: ((-1 == oldIndex) ? paramname : this.dataset.inTableData[oldIndex].name),
										inKey: ((-1 == oldIndex) ? null : this.dataset.inTableData[oldIndex].inKey),
										type: ((-1 == oldIndex) ? 'string' : this.dataset.inTableData[oldIndex].type),
										defaultValue: ((-1 == oldIndex) ? null : this.dataset.inTableData[oldIndex].defaultValue)
									});
									
									temp[paramkey] = true;
								}
							}
						}else{
							alert('未检测到一个参数字段！建议至少一个，不超个三个。');
						}
							
					
					}else{
						
						var txt = sqlMirror.getPlaintext();
						
						var temp = {};
						
						var paramkeys = txt.match(/:[a-zA-Z_0-9]*/g);
						
						if(null != paramkeys){
							
							for(var i=0,len=paramkeys.length; i<len; i++){
								
								var paramkey = paramkeys[i].substring(1);
								
								if(0 == paramkey.indexOf('__getdata_')){
									continue;
								}
								
								if(!temp[paramkey]){
									
									var oldIndex = -1;
									
									for(var j=0,jlen=this.dataset.inTableData.length; j<jlen; j++){
										
										if(this.dataset.inTableData[j].key == paramkey){
											oldIndex = j;
										}
									}
									
									param.push({
										key: paramkey,
										name: ((-1 == oldIndex) ? null : this.dataset.inTableData[oldIndex].name),
										inKey: ((-1 == oldIndex) ? null : this.dataset.inTableData[oldIndex].inKey),
										type: ((-1 == oldIndex) ? 'string' : this.dataset.inTableData[oldIndex].type),
										defaultValue: ((-1 == oldIndex) ? null : this.dataset.inTableData[oldIndex].defaultValue)
									});
									
									temp[paramkey] = true;
								}
							}
						}else{
							alert('未检测到一个参数字段！建议至少一个，不超个三个。');
						}
					}
					
					this.dataset.inTableData = param;
					
					this.onSave();
				},
				onQuoteSearchAsync: function(queryString, cb){
					
					var _this = this;
					
					if($.isBlank(queryString)){
						
						cb(this.dataset.quote.cache || $.get('__GET_DATA_QUOTE_CONFIG_CACHE__'));
						
						return ;
					}
					
					$.http.get({
						url: (appBasePath + '/snail/formext/getdata.do?method=searchConfig'),
						header: {'Accept': 'application/json'},
						data: {
							name: queryString,
							type: this.dataset.formData.fields.type
						},
						onsuccess: function(result, status, xhr){
							
							if(200 == result.code){
								
								var dataList = result.data || _this.dataset.quote.cache || [];
								
								var size = 0;
								var newDataList = [];
								
								for(var i=0,len=dataList.length; i<len; i++){
									
									if(5 <= size){
										break;
									}
									
									if(null == dataList[i].name 
											|| (null != queryString	&& -1 == dataList[i].name.toLowerCase().indexOf(queryString.toLowerCase()))){
										
										continue;
									}
									
									newDataList.push({value: dataList[i].name, mark: dataList[i].mark});
									
									size++;
								}
								
								$.put('__GET_DATA_QUOTE_CONFIG_CACHE__', _this.dataset.quote.cache = newDataList, true);
								
								cb(newDataList);
								
							}else{
								
								cb(_this.dataset.quote.cache);
								
								alert(result.message);
							}
						},
						onerror: function(responseText, status, xhr){
							
							console.log(responseText);
							
							cb(_this.dataset.quote.cache);

							alert('服务异常，STATUS: ' + status);
						}
					});
				},
				onQuoteHandleSelect: function(item){
					
					var _this = this;
					
					this.dataset.quote.value = item.value;
					
					$.http.get({
						url: (appBasePath + '/snail/formext/getdata.do?method=getConfig'),
						header: {'Accept': 'application/json'},
						data:{mark: item.mark},
						onsuccess: function(result, status, xhr){
							
							var data = null;
							
							if(200 == result.code){
								
								_this.dataset.quote.config = result.data;
								
							}else{
								alert(result.message);
							}
						},
						onerror: function(responseText, status, xhr){
							
							console.log(responseText);

							alert('服务异常，STATUS: ' + status);
						}
					});
				},
				onQuoteConfig: function(){
					
					if(null == this.dataset.quote.config){
						
						alert('引用GetDATA配置为空！');
						
						return ;
					}
					
					// 从引用中赋值
					this.basic.db = this.dataset.quote.config.db;
					this.basic.auth = this.dataset.quote.config.auth;
					
					this.dataset.formData.fields.name = '复制_' + this.dataset.quote.config.dataset.script.name;
					this.dataset.formData.fields.type = this.dataset.quote.config.dataset.script.type;
					
					if('groovy' == this.dataset.quote.config.dataset.script.type){
						
						groovyMirror.setValue(this.dataset.quote.config.dataset.script.script);
						
					}else if('http' == this.dataset.quote.config.dataset.script.type){
						
						httpMirror.setValue(this.dataset.quote.config.dataset.script.script);
						
					}else{
						
						sqlMirror.setValue(this.dataset.quote.config.dataset.script.script);
					}
					
					this.dataset.inTableData = this.dataset.quote.config.dataset['in'];
					this.dataset.outTableData = this.dataset.quote.config.dataset['out'];
					
					// 关闭对话框
					this.dataset.quote.dialogVisible = false;
				}
			},
			created: function(){
				this.init();
			}
		});
	}
	
	
	$.extend('app',{
		
		init: function(){
			
			initWindow();
			
			initVue();
		}
	});

	/**
	 *	保存返回数据
	 */
	win['OK'] = function() {
		
		var configData = app.getGetDATA();
		
		var result = $.http.post({
			url: (appBasePath + '/snail/formext/getdata.do?method=saveConfig'),
			header: {'Content-Type': 'application/json', 'Accept': 'application/json'},
			data: configData
		});
		
		if(200 != result.code){
			
			alert(result.message);
			
			return {valid: false, data: null};
		}
				
		return {
			valid: true, 
			data: {
				mark: app.basic.mark,
				button: app.other.formData.fields.button,
				config: configData
			}
		};
	}
	
})(Snail, window, document);